package webmarket.controller;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import webmarket.common.JSONMapper;
import webmarket.common.MarkerController;
import webmarket.common.UserInfoMessages;
import webmarket.common.ValidationObject;
import webmarket.common.MarkerController.MarkerTypes;
import webmarket.jpacontrollers.UserJpaController;
import webmarket.model.User;

@SuppressWarnings("deprecation")
@Controller
@RequestMapping("/registration")
public class RegistrationController extends ControllerBase {
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getRegistrationPage(ModelMap model) {
		return new ModelAndView("registration_full", model);
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView register(ModelMap model,
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "firstname", required = true) String firstname,
			@RequestParam(value = "lastname", required = true) String lastname,
			@RequestParam(value = "city", required = true) String city,
			@RequestParam(value = "address", required = true) String address) {
		model.put("username", username);
		model.put("password", password);
		model.put("firstname", firstname);
		model.put("lastname", lastname);
		model.put("city", city);
		model.put("address", address);
		
		JSONMapper mapper = new JSONMapper();
		UserJpaController ujc = new UserJpaController();
		// Validate given parameters
		boolean error = false;
		if (!StringUtils.isBlank(firstname)) {
			mapper.put(ValidationObject.error("firstname", UserInfoMessages.NEEDED_PARAMETER));
			error = true;
		}
		if (!StringUtils.isBlank(username)) {
			mapper.put(ValidationObject.error("username", UserInfoMessages.NEEDED_PARAMETER));
			error = true;
		}
		if (!StringUtils.isBlank(lastname)) {
			mapper.put(ValidationObject.error("lastname", UserInfoMessages.NEEDED_PARAMETER));
			error = true;
		}
		if (!StringUtils.isBlank(city)) {
			mapper.put(ValidationObject.error("city", UserInfoMessages.NEEDED_PARAMETER));
			error = true;
		}
		if (!StringUtils.isBlank(address)) {
			mapper.put(ValidationObject.error("address", UserInfoMessages.NEEDED_PARAMETER));
			error = true;
		}
		if (password.length() < 5) {
			mapper.put(ValidationObject.error("address", UserInfoMessages.PASSWORD_LENGTH_ERROR));
			error = true;
		}
		if (ujc.userExists(username)) {
			mapper.put(ValidationObject.error("username", UserInfoMessages.USERNAME_EXISTS));
			error = true;
		}

		if (error) {
			model.put("json", mapper.WriteJSON());
			return new ModelAndView("registration_full", model);
		}

		// Create new user
		User user = new User();
		user.setUsername(username);
		user.setCity(city);
		user.setAddress(address);
		user.setFirstname(firstname);
		user.setLastname(lastname);
		user.setRole("USER");
		user.setActive(true);
		user.setMoney(0);
		String encodedPassword = DigestUtils.sha1Hex(password);
		user.setPassword(encodedPassword);
		ujc.create(user);

		// Authenticate
		List<GrantedAuthority> authority = new LinkedList<GrantedAuthority>();
		authority.add(new GrantedAuthorityImpl("USER"));
		org.springframework.security.core.userdetails.User springUser = new org.springframework.security.core.userdetails.User(username,
				encodedPassword, true, true, true, true, authority);
		Authentication authentication = new UsernamePasswordAuthenticationToken(springUser, null, springUser.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(authentication);

		logger.info(MarkerController.getMarker(MarkerTypes.REGISTER),
				"Sikeres regisztráció.");
		
		// Redirect to shop, without GET parameters
		return new ModelAndView("redirect:/shop", new ModelMap());
	}
}
